package com.kashi.service.impl;

import com.kashi.mapper.CollectionMapper;
import com.kashi.mapper.GoodsMapper;
import com.kashi.pojo.Card;
import com.kashi.pojo.Collection;
import com.kashi.pojo.Goods;
import com.kashi.service.CollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;

@Service
public class CollectionServiceImpl implements CollectionService {

    @Autowired
    private CollectionMapper collectionMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public List<Collection> getCollections(Integer userId) {
        return collectionMapper.getCollections(userId);
    }

    @Override
    public void creat(Integer userId,String name) {
        Collection new_collection = new Collection(userId,name,0, LocalDateTime.now(),LocalDateTime.now());

        collectionMapper.insert(new_collection);
    }

    @Override
    public void delete(Integer id) {
        collectionMapper.delete(id);
    }

    @Override
    public List<Card> getContent(Integer id) {
        return collectionMapper.getContent(id);
    }

    @Override
    public void update(Integer id, String name, List<Integer> toAdd, List<Integer> toRemove) {
        
        List<Card> newList = getContent(id);
        
        if(!toAdd.isEmpty()){
            for (int goodsId:
                 toAdd) {
                Goods tgtGoods = goodsMapper.getById(goodsId).get(0);
                Card newCard = new Card();
                newCard.setFromGoods(tgtGoods);
                newList.add(newCard);
            }
        }

        if (!toRemove.isEmpty()){
            for (int goodsId:
                 toRemove) {

                Iterator<Card> iterator = newList.iterator();
                while (iterator.hasNext()) {
                    Card card = iterator.next();
                    if (card.getId() == goodsId) {
                        iterator.remove(); // 使用迭代器的 remove 方法移除当前元素
                    }
                }
            }
        }
        collectionMapper.update(id,name,newList);
    }
}
